/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package l2s.gameserver.handler.voiced;

import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import l2s.commons.crypt.Base64;
import l2s.commons.db.DatabaseFactory;
import l2s.gameserver.handler.IVoicedCommandHandler;
import l2s.gameserver.model.actor.instance.L2PcInstance;

public class ChangePassword implements IVoicedCommandHandler
{
	public static final Logger _log = LoggerFactory.getLogger(ChangePassword.class.getName());
	
	private static final String[] _voicedCommands =
	{
		"password"
	};
	
	@Override
	public boolean useVoicedCommand(String command, L2PcInstance activeChar, String target)
	{
		if (command.equalsIgnoreCase("password") && (target != null))
		{
			StringTokenizer st = new StringTokenizer(target);
			try
			{
				String curpass = null, newpass = null, repeatnewpass = null;
				if (st.hasMoreTokens())
				{
					curpass = st.nextToken();
				}
				if (st.hasMoreTokens())
				{
					newpass = st.nextToken();
				}
				if (st.hasMoreTokens())
				{
					repeatnewpass = st.nextToken();
				}
				
				if (!((curpass == null) || (newpass == null) || (repeatnewpass == null)))
				{
					if (!newpass.equals(repeatnewpass))
					{
						activeChar.sendMessage("Пароли не совпадают!");
						return false;
					}
					if (newpass.length() < 3)
					{
						activeChar.sendMessage("Пароль не может содержать менее 3 символов.");
						return false;
					}
					if (newpass.length() > 30)
					{
						activeChar.sendMessage("Новый пароль содержит более 30 символов. Пожалуйста, введите более короткий пароль.");
						return false;
					}
					
					MessageDigest md = MessageDigest.getInstance("SHA");
					
					byte[] raw = curpass.getBytes("UTF-8");
					raw = md.digest(raw);
					String curpassEnc = Base64.encodeBytes(raw);
					String pass = null;
					int passUpdated = 0;
					
					// SQL connection
					Connection con = DatabaseFactory.getConnection();
					PreparedStatement statement = con.prepareStatement("SELECT password FROM accounts WHERE login=?");
					statement.setString(1, activeChar.getAccountName());
					ResultSet rset = statement.executeQuery();
					if (rset.next())
					{
						pass = rset.getString("password");
					}
					rset.close();
					statement.close();
					con.close();
					
					if (curpassEnc.equals(pass))
					{
						byte[] password = newpass.getBytes("UTF-8");
						password = md.digest(password);
						
						// SQL connection
						Connection con2 = DatabaseFactory.getConnection();
						PreparedStatement ps = con2.prepareStatement("UPDATE accounts SET password=? WHERE login=?");
						ps.setString(1, Base64.encodeBytes(password));
						ps.setString(2, activeChar.getAccountName());
						passUpdated = ps.executeUpdate();
						ps.close();
						con2.close();
						_log.info("Character " + activeChar.getName() + " has changed his password from " + curpassEnc + " to " + Base64.encodeBytes(password));
						if (passUpdated > 0)
						{
							activeChar.sendMessage("You have successfully changed your password!");
						}
						else
						{
							activeChar.sendMessage("The password change was unsuccessful!");
						}
						
					}
					else
					{
						activeChar.sendMessage("CurrentPass doesn't match with your current one.");
						return false;
					}
				}
				else
				{
					activeChar.sendMessage("Не верный формат ввода, введите: .password СтарыйПароль НовыйПароль НовыйПароль");
					return false;
				}
			}
			catch (Exception e)
			{
				activeChar.sendMessage("A problem occured while changing password!");
				_log.warn("", e);
			}
		}
		else
		{
			activeChar.sendMessage("To change your current password, you have to type the command in the following format(without the brackets []): [.changepassword CurrentPass NewPass NewPass]. You should also know that the password is case sensitive.");
			return false;
		}
		return true;
	}
	
	@Override
	public String[] getVoicedCommandList()
	{
		return _voicedCommands;
	}
}
